import daily.commons.Gender
import daily.core.Person
import daily.securety.Account

class PersonController {

    def index() {
        def max = params.max ? params.max as int : 5
        def offset = params.offset ? params.offset as int : 0
        def order = params.order ? params.order as String : 'desc'


        [people: Person.findAll([max: max, offset: offset, sort: 'id', order: order]), total: Person.count, max: max, offset: offset]
    }

    def save() {
        Person person = new Person(params);
        person.save(flush: true);
        assert person.id != null

        redirect(action: 'index')
    }

    def center() {
        Account account = Account.findByName(session.accountName)
        [person: account?.person, genders: Gender.values()]
    }

    def updateInfo() {
        Account account = Account.findByName(session.accountName)
        Person person = account.person
        if (null == person) {
            person = new Person()
        }
        person.properties = params
        if (person.validate()) {
            person.save(flush: true)
            account.person = person
            account.save(flush: true)
        }


        redirect(controller: 'person', action: 'center')

    }

    def uploadPortrait(){
        Account account = Account.findByName(session['accountName'])
        Person person = account.person

        if (null == person) {
            person = new Person()

        }


        def f = request.getFile('portrait')
        if (f.empty) {
            flash.message = 'file cannot be empty'
            redirect( controller: 'person', action: 'center')
            return
        }

        // TODO 将文件存到数据库中
        /*def baseFolder = grailsAttributes.getApplicationContext().getResource("/").getFile().toString()

        def accountHome = new File(baseFolder + '/accountHome/' + session['accountName'])

        if (!accountHome.exists()) {
            accountHome.mkdir()
        }

        f.transferTo(new File(accountHome,'portrait.jpg'))*/

        person.portraitType = request.contentType
        person.portrait = f.getBytes()

        person.save(flush: true)

        account.person = person;

        account.save(flush: true)

        redirect( controller: 'person', action: 'center')
    }


    def viewCurrentPersonsPortrait(){
        response.setHeader("Content-disposition", "attachment; filename=portrait.jpg")
        response.contentType = 'image/jpeg' //'image/jpeg' will do too

        Account account = Account.findByName(session['accountName'])
        Person person = account.person

        byte[] bytes = account.person?.portrait

        response.outputStream << bytes //'myphoto.jpg' will do too
        response.outputStream.flush()


    }


}
